package com.gfl.trivialrestclient.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import com.gfl.trivialrestclient.model.Role;
import com.gfl.trivialrestclient.model.User;

/**
 * Adapter for domain class User to SpringSecurity UserDetails
 * 
 * @author student
 * 
 */
public class UserDetailsAdapter implements UserDetails {

	private static final long serialVersionUID = 1L;

	private User user;

	public UserDetailsAdapter(User user) {
		this.user = user;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Collection<Role> roles = user.getRoles();
		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(
				roles.size());
		for (Role role : user.getRoles()) {
			authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
		}

		return Collections.unmodifiableCollection(authorities);
	}

	@Override
	public String getPassword() {
		return user.getPassword();
	}

	@Override
	public String getUsername() {
		return user.getLogin();
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return !user.getLocked();
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return user.getEnabled();
	}

}
